﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace OperateWebcam
{
    public class DirectShow : IOperateWebcam
    {

        private int videodevice = 0; // zero based index of video capture device to use
        private int videowidth = 640; // Depends on video device caps
        private int videoheight = 480; // Depends on video device caps
        private short videobitsperpixel = 24; // BitsPerPixel values determined by device
        private Control hControl;
        private Capture vedio;
        private IntPtr m_ip = IntPtr.Zero;


        /// <summary>
        /// 私有构造函数
        /// </summary>
        private DirectShow()
        {

        }


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="iDeviceNum">设备参数</param>
        /// <param name="hControl">视频控件</param>
        public DirectShow(int iDeviceNum, Control hControl)
        {
            this.videodevice = iDeviceNum;
            this.videowidth = 640;
            this.videoheight = 480;
            this.videobitsperpixel = 24;
            this.hControl = hControl;
            this.m_ip = IntPtr.Zero;
        }


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="iDeviceNum">设备号</param>
        /// <param name="iWidth">图像宽度</param>
        /// <param name="iHeight">图像高度</param>
        /// <param name="iBPP">每个像素的点数</param>
        /// <param name="hControl">视频控件</param>
        public DirectShow(int iDeviceNum, int iWidth, int iHeight, short iBPP, Control hControl)
        {
            this.videodevice = iDeviceNum;
            this.videowidth = iWidth;
            this.videoheight = iHeight;
            this.videobitsperpixel = iBPP;
            this.hControl = hControl;
            this.m_ip = IntPtr.Zero;
        }


        public void Start()
        {
            this.vedio = new Capture(this.videodevice, this.videowidth, this.videoheight, this.videobitsperpixel, this.hControl);
        }


        public void Close()
        {
            vedio.Dispose();

            if (m_ip != IntPtr.Zero)
            {
                Marshal.FreeCoTaskMem(m_ip);
                m_ip = IntPtr.Zero;
            }
        }


        public Bitmap Save(string path)
        {
            // Release any previous buffer
            if (m_ip != IntPtr.Zero)
            {
                Marshal.FreeCoTaskMem(m_ip);
                m_ip = IntPtr.Zero;
            }

            // capture image
            m_ip = vedio.Click();
            Bitmap curBitmap = new Bitmap(vedio.Width, vedio.Height, vedio.Stride, PixelFormat.Format24bppRgb, m_ip);

            //byte thres = 50;
            //curBitmap = BinaryImage(curBitmap, thres);
            curBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
            curBitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

            return curBitmap;
        }


        public Bitmap Grab(string path)
        {
            // Release any previous buffer
            if (m_ip != IntPtr.Zero)
            {
                Marshal.FreeCoTaskMem(m_ip);
                m_ip = IntPtr.Zero;
            }

            // capture image
            m_ip = vedio.Click();
            Bitmap curBitmap = new Bitmap(vedio.Width, vedio.Height, vedio.Stride, PixelFormat.Format24bppRgb, m_ip);

            byte thres = 50;
            curBitmap = BinaryImage(curBitmap, thres);
            curBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
            curBitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
            
            return curBitmap;



            // If the image is upsidedown
            // b.RotateFlip(RotateFlipType.RotateNoneFlipY);
            // pictureBox1.Image = b;
        }


        /// <summary>
        /// 给定阈值法二值化模块
        /// </summary>
        /// <param name="b"></param>
        /// <param name="threshold"></param>
        /// <returns></returns>
        private Bitmap BinaryImage(Bitmap b, byte threshold)
        {
            int width = b.Width;
            int height = b.Height;
            BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            unsafe
            {
                byte* p = (byte*)data.Scan0;
                int offset = data.Stride - width * 4;
                byte R, G, B, gray;
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        R = p[2];
                        G = p[1];
                        B = p[0];
                        gray = (byte)((R * 19595 + G * 38469 + B * 7472) >> 16);
                        if (gray >= threshold)
                        {
                            p[0] = p[1] = p[2] = 255;
                        }
                        else
                        {
                            p[0] = p[1] = p[2] = 0;
                        }
                        p += 4;
                    }
                    p += offset;
                }
                b.UnlockBits(data);
                return b;
            }
        }

        /// <summary>
        /// Otsu阈值法二值化模块 
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private Bitmap BinaryImage(Bitmap b)
        {
            // 图像灰度化   
            // b = Gray(b);   
            int width = b.Width;
            int height = b.Height;
            byte threshold = 0;
            int[] hist = new int[256];
            int AllPixelNumber = 0, PixelNumberSmall = 0, PixelNumberBig = 0;
            double MaxValue, AllSum = 0, SumSmall = 0, SumBig, ProbabilitySmall, ProbabilityBig, Probability;
            BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            unsafe
            {
                byte* p = (byte*)data.Scan0;
                int offset = data.Stride - width * 4;
                for (int j = 0; j < height; j++)
                {
                    for (int i = 0; i < width; i++)
                    {
                        hist[p[0]]++;
                        p += 4;
                    }
                    p += offset;
                }
                b.UnlockBits(data);
            }
            //计算灰度为I的像素出现的概率   
            for (int i = 0; i < 256; i++)
            {
                AllSum += i * hist[i];     //   质量矩   
                AllPixelNumber += hist[i];  //  质量       
            }
            MaxValue = -1.0;
            for (int i = 0; i < 256; i++)
            {
                PixelNumberSmall += hist[i];
                PixelNumberBig = AllPixelNumber - PixelNumberSmall;
                if (PixelNumberBig == 0)
                {
                    break;
                }
                SumSmall += i * hist[i];
                SumBig = AllSum - SumSmall;

                ProbabilitySmall = SumSmall / PixelNumberSmall;

                ProbabilityBig = SumBig / PixelNumberBig;

                Probability = PixelNumberSmall * ProbabilitySmall * ProbabilitySmall + PixelNumberBig * ProbabilityBig * ProbabilityBig;
                if (Probability > MaxValue)
                {
                    MaxValue = Probability;
                    threshold = (byte)i;
                }
            }
            return this.BinaryImage(b, threshold);
        } // end of OtsuThreshold 2  

    }
}
